<template>
  <op-dialog ref="dialogRef" size="big" height="500px" @confirm="handleConfirm" destroy-on-close>
    <div v-loading.lock="loading" class="transferRoot">
      <!-- 树形控件区域 -->
      <div class="innerTreeWrap">
        <el-input
          v-model="filterText"
          placeholder="Filter keyword"
          :suffix-icon="Search"
          class="filterInput"
        />
        <el-tree
          ref="treeRef"
          :data="treeData"
          :node-key="nodeKey"
          :props="defaultProps"
          :filter-node-method="filterNode"
          show-checkbox
          @check="handleCheck"
        />
      </div>
      <!-- 标签展示区域 -->
      <div class="innerTagWrap">
        <div class="innerTagTitle">
          <span>Selected {{ tagList?.length }}</span>
        </div>
        <div class="innerTagBox">
          <el-tag v-for="(item, index) in tagList" :key="index">
            {{ tagFormatter(item) }}
          </el-tag>
        </div>
      </div>
    </div>
  </op-dialog>
</template>
<script setup>
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
const props = defineProps({
  // 树形控件配置选项
  defaultProps: {
    type: Object,
    default: () => ({
      label: 'name',
      children: 'children',
      disabled: 'disabled',
      isLeaf: 'isLeaf',
      class: 'class',
    }),
  },
  // 树形控件唯一标识
  nodeKey: { type: String, default: 'id' },
  // 后端标识，用于区分可以被选择的数据
  selectType: { type: String, default: '3' },
  // 处理后的树形控件数据
  treeData: { type: Array, default: () => [] },
  // 是否单选
  singleCheck: { type: Boolean, default: false },
  // 标签展示的形式
  tagFormatter: { type: Function, default: item => item.name },
});

// ref
const treeRef = ref();
const dialogRef = ref();

const filterText = ref('');
const loading = ref(false);

const tagList = ref([]);

const emit = defineEmits(['treeCheck', 'transferConfirm']);

const init = () => {
  dialogRef.value.init();
};

const handleConfirm = () => {
  if (tagList.value.length === 0) {
    return ElMessage.warning(`Please select at least one piece of data`);
  }
  emit('transferConfirm', tagList.value);
  dialogRef.value.destroy();
};

const handleCheck = (data, { checkedNodes }) => {
  emit('treeCheck', data, checkedNodes);
  props.singleCheck ? singleTag(data, checkedNodes) : multipleTag(checkedNodes);
};

const singleTag = (data, checkedNodes) => {
  tagList.value = [];
  setTreeCheck([]);
  if (checkedNodes.length > 0) {
    if (!data.children) {
      if (data.type == props.selectType) {
        tagList.value.push(data);
        setTreeCheck([data?.[props.nodeKey]]);
      }
    }
  }
  // emit('itemEvent', { value: tagList.value, prop });
};

const multipleTag = checkedNodes => {
  tagList.value = [];
  checkedNodes?.forEach(item => {
    if (!item.children) {
      if (item.type === props.selectType) tagList.value.push(item);
    }
  });
};

const // 设置目前选中的节点，使用此方法必须设置 node-key 属性
  setTreeCheck = val => {
    nextTick(() => {
      treeRef.value.setCheckedKeys(val);
      // setCheckedKeys
      // (keys, leafOnly) 接收两个参数:
      // 1. 一个需要被选中的多节点 key 的数组
      // 2. 布尔类型的值 如果设置为 true，将只设置选中的叶子节点状态。 默认值是 false.
    });
  };

// 筛选
watch(filterText, val => treeRef.value?.filter(val), { immediate: false });
function filterNode(value, node) {
  if (!value) return true;
  return node[props.defaultProps?.label || 'label']?.toLowerCase()?.includes(value.toLowerCase());
}

defineExpose({ init, loading });
</script>
<style lang="scss" scoped>
.transferRoot {
  height: calc(100% - 22px);
  display: flex;
  .innerTreeWrap {
    flex: 2;
    border: 1px solid rgb(220, 223, 230);
    border-right: 0;
    height: 100%;
    padding: 10px;
    display: flex;
    flex-direction: column;

    overflow: auto;
  }
  .innerTagWrap {
    flex: 3;
    position: relative;
    height: 100%;
    border: solid 1px rgb(220, 223, 230);
    padding: 10px;
    padding-right: 0;
    .innerTagTitle {
      height: 30px;
      display: flex;
      align-items: center;
    }
    .innerTagBox {
      height: calc(100% - 40px);
      padding-right: 15px;
      overflow: auto;
      .el-tag {
        margin: 0 6px 6px 0;
      }
    }
    .el-icon-circle-close {
      position: absolute;
      right: 35px;
      top: 20px;
      &:hover {
        color: var(--el-color-primary);
        cursor: pointer;
      }
    }
  }
}
</style>
